package memberservice

import (
	"errors"
	"fmt"
	"strings"
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/consts"
	"yunj/pkg/yunj/app/data"
	"yunj/pkg/yunj/app/dto"
	"yunj/pkg/yunj/app/enum/admin/departmentenum"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/app/service/admin/adminservice"
	"yunj/pkg/yunj/app/service/admin/departmentservice"
	"yunj/pkg/yunj/app/validator/admin/membervalidator"
	"yunj/pkg/yunj/core/builder"
	"yunj/pkg/yunj/core/builder/builderconsts"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/core/builder/builderenum"
	"yunj/pkg/yunj/core/builder/form"
	"yunj/pkg/yunj/core/builder/form/button"
	"yunj/pkg/yunj/core/builder/form/field"
	"yunj/pkg/yunj/core/builder/table"
	"yunj/pkg/yunj/core/builder/table/col"
	"yunj/pkg/yunj/core/builder/table/col/action"
	"yunj/pkg/yunj/core/builder/table/deftoolbar"
	"yunj/pkg/yunj/core/builder/table/toolbar"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
	"github.com/worklz/go-validate"
	"gorm.io/gorm"
)

type memberPage struct {
}

var MemberPage *memberPage

// 列表构建器
func (s *memberPage) ListBuilder(ctx *gin.Context) *builder.Table {
	hasNormalData := data.Department.HasNormalData()
	return builder.NewTable(ctx, "MemberList").
		State([]builderdto.TableState{
			{Code: stateenum.NORMAL, Title: "正常"},
			{Code: stateenum.RECYLE_BIN, Title: "回收站"},
		}).
		Filter(func(t *builder.Table, state *builderdto.TableState) (filter []form.FieldInterface, err error) {
			filter = []form.FieldInterface{
				field.NewText("keywords", "关键词").SetPlaceholder("模糊匹配，名称/标识"),
			}
			if hasNormalData {
				filter = append(
					filter,
					field.NewTreeCheckbox("department_ids", "部门").SetNodes(departmentservice.GetNormalFormTreeCheckNodes()).SetCorrelation(false, false, false, false),
					field.NewDropdownSearch("postion_ids", "岗位").SetMulti(true).SetOptionsApi(util.BuildAdminUrl("/postion/dropdownSearchOptions")).SetDefault(util.QueryParam(ctx, "postion_ids", "")),
				)
			}
			filter = append(
				filter,
				field.NewDropdownSearch("role_ids", "角色").SetMulti(true).SetOptionsApi(util.BuildAdminUrl("/role/dropdownSearchOptions")).SetDefault(util.QueryParam(ctx, "role_ids", "")),
			)
			return
		}).
		Toolbar(func(t *builder.Table, state *builderdto.TableState) (actions []toolbar.ActionInterface, err error) {
			actions = []toolbar.ActionInterface{
				toolbar.NewOpenPopup("add", "添加").SetClass("layui-icon-add-circle").
					SetUrl(util.BuildAdminUrl("/member/list/add")).SetAuth("yunj_member_list_add"),
			}
			if state.Code == stateenum.RECYLE_BIN {
				actions = append(actions,
					toolbar.NewAsyncEvent(builderenum.TABLE_EVENT_TYPE_NORMAL, "恢复正常").SetDropdown(true).SetAuth("yunj_member_list_normal"),
					toolbar.NewAsyncEvent(builderenum.TABLE_EVENT_TYPE_DELETED, "永久删除").SetDropdown(true).SetAuth("yunj_member_list_deleted"),
				)
			} else {
				actions = append(actions,
					toolbar.NewAsyncEvent(builderenum.TABLE_EVENT_TYPE_RECYLE_BIN, "移入回收站").SetDropdown(true).SetAuth("yunj_member_list_recyle_bin"),
				)
			}
			return
		}).
		DefaultToolbar([]deftoolbar.ActionInterface{
			deftoolbar.NewFilter(),
			deftoolbar.NewExport().SetAuth("yunj_member_list_export"),
		}).
		Cols(func(t *builder.Table, state *builderdto.TableState) (cols []table.ColInterface, err error) {
			roleEnumOptions, err := model.GetNormalRoleTableColOptions()
			if err != nil {
				return
			}
			cols = []table.ColInterface{
				col.NewCheckbox("id", "ID"),
				col.NewText("name", "姓名"),
				col.NewText("username", "账户"),
			}
			// 部门/岗位
			if hasNormalData {
				var departmentPostionEnumOptions []builderdto.TableColOption
				departmentPostionEnumOptions, err = departmentservice.GetNormalPostionTableColOptions()
				if err != nil {
					return
				}
				cols = append(
					cols,
					col.NewEnum("department_ids", "部门").SetOptions(departmentservice.GetNormalTableColOptions()),
					col.NewEnum("department_postion_ids", "岗位").SetOptions(departmentPostionEnumOptions),
				)
			}
			// 角色...
			cols = append(
				cols,
				col.NewEnum("role_ids", "角色").SetOptions(roleEnumOptions),
				col.NewText("last_login_ip", "最近登录IP").SetAlign(builderconsts.ALIGN_CENTER),
				col.NewDatetime("last_login_at", "最近登录时间").SetAlign(builderconsts.ALIGN_CENTER),
				col.NewDatetime("created_at", "添加时间").SetAlign(builderconsts.ALIGN_CENTER),
				col.NewDatetime("updated_at", "最近修改时间").SetAlign(builderconsts.ALIGN_CENTER),
			)

			actionCol := col.NewAction("操作").SetOptions([]action.ActionInterface{
				action.NewOpenPopup("edit", "详情").SetClass("layui-icon-survey").SetUrl(util.BuildAdminUrl("/member/list/edit")).SetAuth("yunj_member_list_edit"),
			})
			if state.Code == stateenum.RECYLE_BIN {
				actionCol.Options = append(actionCol.Options,
					action.NewAsyncEvent(builderenum.TABLE_EVENT_TYPE_NORMAL, "恢复正常").SetDropdown(true).SetAuth("yunj_member_list_normal"),
					action.NewAsyncEvent(builderenum.TABLE_EVENT_TYPE_DELETED, "永久删除").SetDropdown(true).SetAuth("yunj_member_list_deleted").
						SetConfirmFormFields(field.NewTxt("tips", "确认删除？")).SetShow(fmt.Sprintf("d.id!==%d", 1)),
				)
			} else {
				actionCol.Options = append(actionCol.Options,
					action.NewAsyncEvent(builderenum.TABLE_EVENT_TYPE_RECYLE_BIN, "移入回收站").SetDropdown(true).
						SetAuth("yunj_member_list_recyle_bin").SetShow(fmt.Sprintf("d.id!==%d", 1)),
				)
			}
			cols = append(cols, actionCol)
			return
		}).
		Validator(func(t *builder.Table) (validate.ValidatorInterface, error) {
			v := &membervalidator.Member{}
			v.InitValidator(v)
			return v, nil
		}).
		Count(func(t *builder.Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableCountResult, err error) {
			var filterFormParam dto.AdminMemberPageListFilterFormParam
			util.MapToStruct(requestParam.Uint64FilterData(), &filterFormParam)
			query := s.listBuilderFilterQuery(requestParam, &filterFormParam)
			err = query.Count(&res.Count).Error
			if err != nil {
				err = fmt.Errorf("数据量查询异常！%v", err)
				return
			}
			return
		}).
		Items(func(t *builder.Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableItemsResult, err error) {
			var filterFormParam dto.AdminMemberPageListFilterFormParam
			util.MapToStruct(requestParam.Uint64FilterData(), &filterFormParam)
			query := s.listBuilderFilterQuery(requestParam, &filterFormParam)
			query.Select("m.*").Order("m.created_at desc").Offset(requestParam.Offset()).Limit(requestParam.Limit())
			var memberItems []*model.AdminMember
			if err = query.Find(&memberItems).Error; err != nil {
				err = fmt.Errorf("数据查询异常！%v", err)
				return
			}
			res.Items, err = s.listBuilderItemsHandle(memberItems)
			return
		}).
		Event(func(t *builder.Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableEventResult, err error) {
			handleEventRes, err := builderenum.HandleEvent(ctx, &model.AdminMember{}, requestParam.EventCode, requestParam.Pks, func(param *builderenum.EventDbParam, e *builderenum.Event, pks []any) (err error) {
				if e.Value == builderenum.TABLE_EVENT_TYPE_DELETED {
					param.Data["username"] = gorm.Expr("concat(`username`, '_del_', ?)", time.Now().In(time.Local).Format("20060102150405"))
					param.Where = append(param.Where, []any{"id <> ?", 1})
				} else if e.Value == builderenum.TABLE_EVENT_TYPE_RECYLE_BIN {
					param.Where = append(param.Where, []any{"id <> ?", 1})
				}
				return
			})
			if err != nil {
				return
			}
			if handleEventRes != nil {
				res.ResponseJsonData = handleEventRes
				return
			}
			err = fmt.Errorf("异常事件[%v]", requestParam.EventCode)
			return
		})
}

// 列表数据项处理
func (s *memberPage) listBuilderItemsHandle(items []*model.AdminMember) (resItems []*dto.AdminMemberPageListItemResponse, err error) {
	if len(items) <= 0 {
		return
	}
	ids := make([]uint64, 0, len(items))
	for _, item := range items {
		ids = append(ids, item.Id)
	}
	// 角色ids
	var memberRoles []*model.AdminMemberRole
	err = global.MySQL.Model(&model.AdminMemberRole{}).Where("member_id in ?", ids).Find(&memberRoles).Error
	if err != nil {
		err = fmt.Errorf("关联角色查询异常！%v", err)
		return
	}
	memberRoleIds := map[uint64][]uint64{}
	for _, memberRole := range memberRoles {
		if _, exists := memberRoleIds[memberRole.MemberId]; !exists {
			memberRoleIds[memberRole.MemberId] = []uint64{}
		}
		memberRoleIds[memberRole.MemberId] = append(memberRoleIds[memberRole.MemberId], memberRole.RoleId)
	}
	resItems = make([]*dto.AdminMemberPageListItemResponse, 0, len(items))
	for _, item := range items {
		resItem := &dto.AdminMemberPageListItemResponse{
			Id:          item.Id,
			Name:        item.Name,
			Username:    item.Username,
			LastLoginIp: item.LastLoginIp,
			CreatedAt:   item.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:   item.UpdatedAt.Format("2006-01-02 15:04:05"),
		}
		// last_login_at
		if item.LastLoginAt != nil {
			resItem.LastLoginAt = item.LastLoginAt.Format("2006-01-02 15:04:05")
		}
		// role_ids
		if roleIds, exists := memberRoleIds[item.Id]; exists {
			resItem.RoleIds = roleIds
		}
		resItems = append(resItems, resItem)
	}
	// 部门岗位
	if data.Department.HasNormalData() {
		// 部门ids
		var memberDepartments []*model.AdminMemberDepartment
		err = global.MySQL.Model(&model.AdminMemberDepartment{}).Where("member_id in ?", ids).Find(&memberDepartments).Error
		if err != nil {
			err = fmt.Errorf("关联角色查询异常！%v", err)
			return
		}
		memberDepartmentIds := map[uint64][]uint64{}
		for _, memberDepartment := range memberDepartments {
			if _, exists := memberDepartmentIds[memberDepartment.MemberId]; !exists {
				memberDepartmentIds[memberDepartment.MemberId] = []uint64{}
			}
			memberDepartmentIds[memberDepartment.MemberId] = append(memberDepartmentIds[memberDepartment.MemberId], memberDepartment.DepartmentId)
		}
		// 部门岗位ids
		var memberDepartmentPostions []*model.AdminMemberDepartmentPostion
		err = global.MySQL.Model(&model.AdminMemberDepartmentPostion{}).Where("member_id in ?", ids).Find(&memberDepartmentPostions).Error
		if err != nil {
			err = fmt.Errorf("关联角色查询异常！%v", err)
			return
		}
		memberDepartmentPostionIds := map[uint64][]uint64{}
		for _, memberDepartmentPostion := range memberDepartmentPostions {
			if _, exists := memberDepartmentPostionIds[memberDepartmentPostion.MemberId]; !exists {
				memberDepartmentPostionIds[memberDepartmentPostion.MemberId] = []uint64{}
			}
			memberDepartmentPostionIds[memberDepartmentPostion.MemberId] = append(memberDepartmentPostionIds[memberDepartmentPostion.MemberId], memberDepartmentPostion.DepartmentPostionId)
		}
		for _, resItem := range resItems {
			// department_ids
			if departmentIds, exists := memberDepartmentIds[resItem.Id]; exists {
				resItem.DepartmentIds = departmentIds
			}
			// department_postion_ids
			if departmentPostionIds, exists := memberDepartmentPostionIds[resItem.Id]; exists {
				resItem.DepartmentPostionIds = departmentPostionIds
			}
		}
	}
	return
}

// 列表过滤条件查询对象
func (s *memberPage) listBuilderFilterQuery(requestParam *builderdto.TableRequestParam, filterFormParam *dto.AdminMemberPageListFilterFormParam) (query *gorm.DB) {
	tablePrefix := global.Config.Database.TablePrefix
	query = global.MySQL.Table(tablePrefix + "admin_member m")
	// ids
	if len(requestParam.Pks) > 0 {
		query.Where("m.id in ?", requestParam.Pks)
	}
	// state
	stateWhere := stateenum.NORMAL
	if stateCode, ok := stateenum.IsValue(requestParam.State); ok {
		stateWhere = stateCode
	}
	query.Where("m.state = ?", stateWhere)
	// keywords
	if filterFormParam.Keywords != "" {
		keywordsWhere := "%" + filterFormParam.Keywords + "%"
		query.Where("m.name like ? or m.username like ?", keywordsWhere, keywordsWhere)
	}
	// department_ids
	if len(filterFormParam.DepartmentIds) > 0 {
		// 获取所有下级部门
		query.Where(
			"exists (?)",
			global.MySQL.Table(tablePrefix+"admin_member_department md").
				Joins("join "+tablePrefix+"admin_department as d on d.id=md.department_id").
				Select("1").Where("md.member_id=m.id and d.state=? and md.department_id in ?", stateenum.NORMAL, filterFormParam.DepartmentIds),
		)
	}
	// postion_ids
	if len(filterFormParam.PostionIds) > 0 {
		query.Where(
			"exists (?)",
			global.MySQL.Table(tablePrefix+"admin_member_department_postion mdp").
				Joins("join "+tablePrefix+"admin_department_postion as dp on dp.id=mdp.department_postion_id").
				Joins("join "+tablePrefix+"admin_department as d on d.id=dp.department_id").
				Joins("join "+tablePrefix+"admin_postion as p on p.id=dp.postion_id").
				Select("1").Where("mdp.member_id=m.id and dp.state=? and d.state=? and p.state=? and dp.postion_id in ?", stateenum.NORMAL, stateenum.NORMAL, stateenum.NORMAL, filterFormParam.PostionIds),
		)
	}
	// role_ids
	if len(filterFormParam.RoleIds) > 0 {
		query.Where(
			"exists (?)",
			global.MySQL.Table(tablePrefix+"admin_member_role mr").
				Joins("join "+tablePrefix+"admin_role as r on r.id=mr.role_id").
				Select("1").Where("mr.member_id=m.id and r.state=? and mr.role_id in ?", stateenum.NORMAL, filterFormParam.RoleIds),
		)
	}
	return
}

// 表单构建器
func (s *memberPage) FormBuilder(ctx *gin.Context, isEdit, isInfo bool) (formBuilder *builder.Form) {
	hasNormalData := data.Department.HasNormalData()
	formBuilder = builder.NewForm(ctx, "MemberForm").
		Field(func(f *builder.Form, tab *builderdto.FormTab) (fields []form.FieldInterface, err error) {
			// 密码
			passwordField := field.NewPassword("password", "密码").SetVerify("alphaDash|max:32").SetDesc("只能输入字母/数字/下划线_及短横线-")
			if !isEdit {
				passwordField.SetPlaceholder("默认密码：" + consts.ADMIN_MEMBER_DEFAULT_PASSWORD)
			}
			// 字段
			fields = []form.FieldInterface{
				field.NewLine("line1", "基础信息"),
				field.NewText("username", "账户").SetVerify("required|alphaDash|max:45").SetDesc("只能输入字母/数字/下划线_及短横线-"),
				passwordField,
				field.NewText("name", "姓名").SetVerify("required|chsDash|max:32").SetDesc("只能输入汉字、字母、数字和下划线_及破折号-"),
			}
			// 部门/岗位
			if hasNormalData {
				fields = append(
					fields,
					field.NewLine("line2", "部门/岗位"),
					field.NewTreeCheckbox("department_ids", "部门").SetNodes(departmentservice.GetNormalFormTreeCheckNodes()).SetCorrelation(false, false, false, false).SetDesc("部门选择后，才能进行部门下的岗位选择").SetReadonly(isInfo),
					field.NewDropdownSearch("department_postion_ids", "岗位").SetOptionsApi(util.BuildAdminUrl("/member/departmentPostionDropdownSearchOptions")).SetMulti(true).SetDesc("岗位的增减会自动增减岗位对应的角色").SetReadonly(isInfo),
				)
			}
			// 角色
			fields = append(
				fields,
				field.NewLine("line3", "角色"),
				field.NewDropdownSearch("role_ids", "角色").SetOptionsApi(util.BuildAdminUrl("/role/dropdownSearchOptions")).SetMulti(true).SetReadonly(isInfo),
			)
			// 编辑
			if isEdit {
				fields = append(fields, field.NewHidden("id"))
				var loadRes dto.AdminMemberPageFormLoadResponse
				loadRes, err = builder.FormLoadValue[dto.AdminMemberPageFormLoadResponse](f)
				if err != nil {
					return
				}
				if adminservice.GetLoginMemberId(ctx) != 1 && loadRes.Id == 1 {
					for _, v := range fields {
						if err = v.SetFieldReadonly(true); err != nil {
							err = fmt.Errorf("初始超管账户设置字段只读异常！%v", err)
							return
						}
					}
				}
			}
			// 设置栅格布局
			for _, v := range fields {
				v.SetFieldGrid([]any{12, 12, 12, 12, "6 l3 r3"})
			}
			return
		}).
		Button(func(f *builder.Form) (buttons []form.ButtonInterface, err error) {
			if isEdit {
				var loadRes dto.AdminMemberPageFormLoadResponse
				loadRes, err = builder.FormLoadValue[dto.AdminMemberPageFormLoadResponse](f)
				if err != nil {
					return
				}

				if adminservice.GetLoginMemberId(ctx) != 1 && loadRes.Id == 1 {
					// 初始超管账户不允许修改
					return
				}
				buttons = []form.ButtonInterface{
					button.NewReset(),
					button.NewSubmit(),
				}
			} else {
				buttons = []form.ButtonInterface{
					button.NewClear(),
					button.NewSubmit(),
				}
			}
			return
		}).
		Validator(func(f *builder.Form) (validate.ValidatorInterface, error) {
			v := &membervalidator.Member{
				GinContext: ctx,
				IsInfo:     isInfo,
			}
			v.InitValidator(v)
			return v, nil
		}).
		Submit(func(f *builder.Form, values map[string]any) (res builderdto.FormSubmitResult, err error) {
			var dbMember *model.AdminMember
			dbMember = util.MapKeyValue(values, "dbMember", dbMember)
			var dbMemberDepartments []*model.AdminMemberDepartment
			dbMemberDepartments = util.MapKeyValue(values, "dbMemberDepartments", dbMemberDepartments)
			var dbMemberDepartmentPostions []*model.AdminMemberDepartmentPostion
			dbMemberDepartmentPostions = util.MapKeyValue(values, "dbMemberDepartmentPostions", dbMemberDepartmentPostions)
			var dbMemberRoles []*model.AdminMemberRole
			dbMemberRoles = util.MapKeyValue(values, "dbMemberRoles", dbMemberRoles)
			if dbMember.Id > 0 {
				// 修改
				fields := []string{"username", "name", "updated_at"}
				if dbMember.PasswordHash != "" {
					fields = append(fields, "password_hash", "password_salt")
				}
				err = global.MySQL.Select(fields).Save(dbMember).Error
				if err != nil {
					err = fmt.Errorf("编辑失败！%v", err.Error())
					return
				}
			} else {
				// 新增
				dbMember.Pid = adminservice.GetLoginMemberId(ctx)
				err = global.MySQL.Create(dbMember).Error
				if err != nil {
					err = fmt.Errorf("新增失败！%v", err.Error())
					return
				}
				for _, v := range dbMemberDepartments {
					v.MemberId = dbMember.Id
				}
				for _, v := range dbMemberDepartmentPostions {
					v.MemberId = dbMember.Id
				}
				for _, v := range dbMemberRoles {
					v.MemberId = dbMember.Id
				}
			}
			// 个人信息不允许修改部门、岗位、角色
			if !isInfo {
				if hasNormalData {
					// member_department
					err = global.MySQL.Transaction(func(tx *gorm.DB) (err error) {
						err = global.MySQL.Where("member_id = ?", dbMember.Id).Delete(&model.AdminMemberDepartment{}).Error
						if err != nil {
							err = fmt.Errorf("部门关系数据处理异常，请刷新页面后重试！%v", err)
							return
						}
						err = global.MySQL.CreateInBatches(dbMemberDepartments, len(dbMemberDepartments)).Error
						if err != nil {
							err = fmt.Errorf("部门关系数据保存异常，请刷新页面后重试！%v", err)
							return
						}
						return
					})
					if err != nil {
						return
					}
					// member_department_postion
					err = global.MySQL.Transaction(func(tx *gorm.DB) (err error) {
						err = global.MySQL.Where("member_id = ?", dbMember.Id).Delete(&model.AdminMemberDepartmentPostion{}).Error
						if err != nil {
							err = fmt.Errorf("部门岗位关系数据处理异常，请刷新页面后重试！%v", err)
							return
						}
						err = global.MySQL.CreateInBatches(dbMemberDepartmentPostions, len(dbMemberDepartmentPostions)).Error
						if err != nil {
							err = fmt.Errorf("部门岗位关系数据保存异常，请刷新页面后重试！%v", err)
							return
						}
						return
					})
					if err != nil {
						return
					}
				}
				// member_role
				err = global.MySQL.Transaction(func(tx *gorm.DB) (err error) {
					err = global.MySQL.Where("member_id = ?", dbMember.Id).Delete(&model.AdminMemberRole{}).Error
					if err != nil {
						err = fmt.Errorf("角色关系数据处理异常，请刷新页面后重试！%v", err)
						return
					}
					err = global.MySQL.CreateInBatches(dbMemberRoles, len(dbMemberRoles)).Error
					if err != nil {
						err = fmt.Errorf("角色关系数据保存异常，请刷新页面后重试！%v", err)
						return
					}
					return
				})
				if err != nil {
					return
				}
			}
			res.Reload = true
			return
		})

	if isEdit {
		formBuilder.Load(func(f *builder.Form) (res any, err error) {
			var id uint64
			var member model.AdminMember
			if isInfo {
				member = *adminservice.GetLoginMember(ctx)
				id = member.Id
			} else {
				id = util.QueryUint64Param(ctx, "id")
				if id <= 0 {
					err = fmt.Errorf("异常数据")
					return
				}
				dbErr := global.MySQL.Where("`id` = ? and state <> ?", id, stateenum.DELETED).First(&member).Error
				if (dbErr != nil && !errors.Is(dbErr, gorm.ErrRecordNotFound)) || member.Id <= 0 {
					err = fmt.Errorf("数据获取异常！%v", dbErr)
					return
				}
			}
			resData := dto.AdminMemberPageFormLoadResponse{
				Id:       member.Id,
				Username: member.Username,
				Name:     member.Name,
			}
			// 角色数据
			var roleIds []uint64
			dbErr := global.MySQL.Model(&model.AdminMemberRole{}).Where("`member_id` = ?", id).Pluck("role_id", &roleIds).Error
			if dbErr != nil {
				err = fmt.Errorf("成员角色数据获取异常！%v", dbErr)
				return
			}
			resData.RoleIds = roleIds
			// 部门/岗位数据
			if hasNormalData {
				var departmentIds []uint64
				dbErr = global.MySQL.Model(&model.AdminMemberDepartment{}).Where("`member_id` = ?", id).Pluck("department_id", &departmentIds).Error
				if dbErr != nil {
					err = fmt.Errorf("成员部门数据获取异常！%v", dbErr)
					return
				}
				resData.DepartmentIds = departmentIds
				var departmentPostionIds []uint64
				dbErr = global.MySQL.Model(&model.AdminMemberDepartmentPostion{}).Where("`member_id` = ?", id).Pluck("department_postion_id", &departmentPostionIds).Error
				if dbErr != nil {
					err = fmt.Errorf("成员部门岗位数据获取异常！%v", dbErr)
					return
				}
				resData.DepartmentPostionIds = departmentPostionIds
			}
			res = resData
			return
		})
	}
	return
}

// 部门岗位下拉搜索可选项
func (s *memberPage) DepartmentPostionDropdownSearchOptions(ctx *gin.Context) (options []builderdto.Option, err error) {
	param := util.QueryParams(ctx)
	departmentIdsStr := util.MapKeyValue(param, "department_ids", "")
	if departmentIdsStr == "" {
		return
	}
	departmentIds := util.ToUint64Slice(strings.Split(departmentIdsStr, ","))
	if len(departmentIds) == 0 {
		return
	}
	tablePrefix := global.Config.Database.TablePrefix
	query := global.MySQL.Table(tablePrefix+"admin_department_postion dp").
		Joins("join "+tablePrefix+"admin_department as d on dp.department_id = d.id").
		Joins("join "+tablePrefix+"admin_postion as p on dp.postion_id = p.id").
		Where("dp.department_id in ? and dp.state = ? and d.state = ? and p.state = ?", departmentIds, stateenum.NORMAL, stateenum.NORMAL, stateenum.NORMAL).
		Select("dp.id", "dp.type", "d.type as department_type", "d.name as department_name", "p.name as postion_name").
		Group("dp.id").Order("d.sort asc,p.sort asc").Limit(20)
	if values, exists := param["values"]; exists {
		if values, ok := values.(string); ok && values != "" {
			query = query.Where("dp.id in ?", strings.Split(values, ","))
		}
	}
	if keywords, exists := param["keywords"]; exists {
		if keywords, ok := keywords.(string); ok && keywords != "" {
			likeKeywords := "%" + keywords + "%"
			query = query.Where("(d.name like ? or p.name like ?)", likeKeywords, likeKeywords)
		}
	}
	var items []dto.AdminMemberPageDepartmentPostionDropdownSearchItem
	dbErr := query.Find(&items).Error
	if dbErr != nil {
		err = fmt.Errorf("数据查询异常！%v", dbErr)
		return
	}
	options = make([]builderdto.Option, 0, len(items))
	for _, item := range items {
		options = append(options, builderdto.Option{
			Value: item.Id,
			Label: fmt.Sprintf("【%s】%s【%s】%s", departmentenum.TypeByValue(item.DepartmentType).GetDesc(), item.DepartmentName, departmentenum.PostionTypeByValue(item.Type).GetDesc(), item.PostionName),
		})
	}
	return
}

// 下拉搜索选项
func (s *memberPage) DropdownSearchOptions(ctx *gin.Context) (options []builderdto.Option, err error) {
	param := util.QueryParams(ctx)
	query := global.MySQL.Where("state = ?", stateenum.NORMAL).Limit(20).Select("id,name,username")
	if values, exists := param["values"]; exists {
		if values, ok := values.(string); ok && values != "" {
			query = query.Where("id in ?", strings.Split(values, ","))
		}
	}
	if keywords, exists := param["keywords"]; exists {
		if keywords, ok := keywords.(string); ok && keywords != "" {
			likeKeywords := "%" + keywords + "%"
			query = query.Where("(name like ? or username like ?)", likeKeywords, likeKeywords)
		}
	}
	var items []model.AdminMember
	dbErr := query.Find(&items).Error
	if dbErr != nil {
		err = fmt.Errorf("数据查询异常！%v", dbErr)
		return
	}
	options = make([]builderdto.Option, 0, len(items))
	for _, item := range items {
		options = append(options, builderdto.Option{Value: item.Id, Label: item.Name + "【" + item.Username + "】"})
	}
	return
}
